import typeOfUtils from "@/utils/type-of-utils";

let dateApp
let isInsert = false

class dataValue {
  x = 0
  y = 0
  debuggerLogData = []
  debuggerNetworkLogData = []
  eventNumber = 0
  srollTop = {
    console: 0,
    network: 0,
    storge: 0
  }
  showValue = 'console'
}

/**
 * @return {dataValue}
 */
export function getDate() {
  return dateApp?.globalData?.pageConsoleData
}

export const ClipboardUtils = {
  /**
   * 设置粘贴板数据
   * @param text
   * 如果未设置参数，则清空数据
   */
  setClipboardText(text) {
    if (typeOfUtils.isObject(text)) {
      text = JSON.stringify(text)
    }
    return new Promise((resolve, reject) => {
      uni.setClipboardData({
        data: text,
        success: () => {
          resolve()
        },
        fail: () => {
          reject()
        }
      })
    })
  },

  getClipboardText() {
    return new Promise((resolve, reject) => {
      uni.getClipboardData({
        success: ({data}) => {
          resolve(data)
        },
        fail: () => {
          reject()
        }
      })
    })
  }
}

export function destroyEvent() {
  getDate().eventNumber--
  if (getDate().eventNumber <= 0) {
    uni.$off('debugger-refresh-network');
    uni.$off('debugger-refresh-log');
  }
}

export function addEvent() {
  getDate().eventNumber++
}

export function setPosition(x, y) {
  getDate().x = x
  getDate().y = y
}

export const debuggerModule = {
  addNetworkLog(info, options, req) {
    getDate().debuggerNetworkLogData.push({info, options, req});
    uni.$emit('debugger-refresh-network');
  },
  addLog(info) {
    getDate().debuggerLogData.push(info);
    uni.$emit('debugger-refresh-log', false);
  }
}

function pad(num, n) {
  let strNum = num.toString();
  let len = strNum.length;
  while (len < n) {
    strNum = "0" + strNum;
    len++;
  }
  return strNum;
}

function getNowTimeString() {
  const d = new Date();
  return pad(d.getHours(), 2) + ':' + pad(d.getMinutes(), 2) + ':' + pad(d.getSeconds(), 2);
}

export function installPageConsoleHook(app) {
  if (isInsert) {
    return
  }
  isInsert = true
  app.$vm.$set(app.globalData, 'pageConsoleData', new dataValue())
  dateApp = app
  let console_log = console.log
  let console_error = console.error
  let console_info = console.info
  let console_warn = console.warn
  console.log = function (...arg) {
    debuggerModule.addLog({time: getNowTimeString(), type: 'log', objects: arg});
    console_log(...arg)
  }
  console.error = function (...arg) {
    debuggerModule.addLog({time: getNowTimeString(), type: 'error', objects: arg});
    console_error(...arg)
  }
  console.info = function (...arg) {
    debuggerModule.addLog({time: getNowTimeString(), type: 'info', objects: arg});
    console_info(...arg)
  }
  console.warn = function (...arg) {
    debuggerModule.addLog({time: getNowTimeString(), type: 'warn', objects: arg});
    console_warn(...arg)
  }
  /* 拦截请求 */
  uni.addInterceptor('request', {
    invoke(args) {
      // request 触发前拼接 url
      const addInterceptorRequestData = {
        data: args.data,
        method: args.method || 'GET',
        sourceUrl: args.url,
        url: args.url,
        status: 0,
        requestTime: getNowTimeString()
      }
      let _complete = args.complete;
      args.complete = function (e) {
        _complete && _complete(e)
        addInterceptorRequestData.status = e.statusCode
        addInterceptorRequestData.responseTime = getNowTimeString()
        if (e.statusCode !== 200) {
          addInterceptorRequestData.type = 'error'
        } else {
          addInterceptorRequestData.type = 'log'
        }
        debuggerModule.addNetworkLog(
          addInterceptorRequestData,
          args,
          e
        );
      }
    },
  })
}
